﻿@model JewererBasic.Models.OrderViewModel



@{
    ViewBag.Title = "Create Order";
}

<h2>Create Order</h2>

@using (Html.BeginForm())
{
    <fieldset>
    <div>
        <a href="/Order/Index">
            <input type="button" value="BACK" />
        </a>
    </div>
     
    <div>
        <table>
            <tr>
                <td>
                    <fieldset>
                        <legend>ORDER INFORMATION</legend>
                        <div>
                            <table>
                                <tr>
                                    <td>
                                        <strong>Order Id</strong>
                                    </td>
                                    <td>@Html.TextBoxFor(m => m.IdOrder, new { title = "Input order id.", placeholder = "Order Id", id = "orderid", @class="textInput requiredInput" })
                                    </td>
                                    <td colspan="4">
                                        <span class="requireSpan" id="requireIdOrder" style="color: red; display: none">This field is required.</span>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <strong>Customer Id</strong>
                                    </td>
                                    <td>@Html.TextBoxFor(m => m.IdCustomer, new { title = "Input customer id.", placeholder = "Customer Id", id = "customerid", @class="textInput requiredInput" })
                                    </td>
                                    <td colspan="4">
                                        <span class="requireSpan" id="requireCustomer" style="color: red; display: none">This
                                            field is required.</span>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <strong>Start Week</strong>
                                    </td>
                                    <td style="width: 320px;">@Html.TextBoxFor(m => m.StartWeek, new { type = "number", min = "0", @class = "inputItem requiredInput", title = "Input start week.", placeholder = "Start Week", id = "startweek" })
                                    </td>
                                    <td>
                                        <strong>Finish Week</strong>
                                    </td>
                                    <td style="width: 320px;">@Html.TextBoxFor(m => m.FinishWeek, new { type = "number", min = "0", @class = "inputItem requiredInput", title = "Input finish week.", placeholder = "Finish Week", id = "finishweek" })
                                    </td>
                                </tr>
                                @*<tr>
                                    <td>
                                        <strong>Product Qty</strong>
                                    </td>
                                    <td style="width: 320px;">@Html.TextBoxFor(m => m.Quantity, new { type = "number", min = "0", @class = "inputItem requiredInput", title = "A maximum number of products in bags.", placeholder = "Quantity", id = "quantity" })
                                    </td>
                                </tr>*@
                                <tr>
                                    <td colspan="4" style="height: 25px;">
                                        <span id="invalidWeek" style="display: none; height: 20px; color: red;"></span>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </fieldset>
                </td>
            </tr>
            <tr>
                <td>
                    <fieldset>
        <legend>ADD PRODUCTs</legend>
        <div>
            <input type="button" value="ADD" id="btnAddNewRow" />
        </div>
        <div style="height: 25px"></div>
        <div>
            <div id="contentPaste" contenteditable="true">Paste copied items in here...</div>
        </div>
        <fieldset id="myfieldset">
            <legend>PRODUCTs</legend>
            <p id="notification" style="color: red; display: none"></p>
            <div id="productionArea" />
        </fieldset>
    </fieldset>
                </td>
            </tr>
        </table>
    </div>   
        <div>
            <input type="button" id="submitFinish" value="FINISH" name="submitButton" title = "Submit this order and save into database."/>
            <input type="button" id="submitClear" value="CLEAR" name="submitButton" title = "Clear all controls."/>
        </div>
    </fieldset>
    
}
@section Scripts {
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="@Url.Content("~/Scripts/json2.min.js")" type="text/javascript"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script src="@Url.Content("~/Scripts/json2.min.js")" type="text/javascript"></script>
    
    @*get data*@
    <script type="text/javascript">

        $(function () {
            window.alert = function (message) {
                $(document.createElement('div'))
                    .attr({ title: 'Information', 'class': 'alert' })
                    .html(message)
                    .dialog({
                        buttons: { OK: function () { $(this).dialog('close'); } },
                        close: function () { $(this).remove(); },
                        draggable: true,
                        modal: true,
                        resizable: false,
                        width: 'auto'
                    });
            };
        });

        $("#submitFinish").click(function () {
            //$(this)

            var flag = 0;

            var IdOrder = $('#orderid').val();
            var IdCustomer = $('#customerid').val();
            var StartWeek = $('#startweek').val();
            var FinishWeek = $('#finishweek').val();
            //var Quantity = $('#quantity').val();

            if (IdCustomer.length == 0 || IdOrder.length == 0
                || StartWeek.length == 0 || parseInt(StartWeek) <= 0
                || FinishWeek.length == 0 || parseInt(FinishWeek) <= 0) {


                if (FinishWeek.length == 0 || parseInt(FinishWeek) <= 0) {
                    $("#invalidWeek").text("This fields is required and value has to be greater 0.").show().fadeOut(5000);
                    $("#finishweek").focus();
                }

                if (StartWeek.length == 0 || parseInt(StartWeek) <= 0) {
                    $("#invalidWeek").text("This fields is required and value has to be greater 0.").show().fadeOut(5000);
                    $("#startweek").focus();
                }

                if (IdCustomer.length == 0) {
                    $("#requireCustomer").text("This fields is required.").show().fadeOut(5000);
                    $("#customerid").focus();
                }

                if (IdOrder.length == 0) {
                    $("#requireIdOrder").text("This fields is required.").show().fadeOut(5000);
                    $("#orderid").focus();
                }
            } else {

                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("IsOrderExisted", "Order")',
                    data: { "id": IdOrder },
                    dataType: "json",
                    async: false,
                    beforeSend: function () {//alert();
                    },
                    success: function (data) {
                        if (data.result == true) {
                            $("#requireIdOrder").text("Order id has already existed in the system. Please check again.").show().fadeOut(5000);
                            flag = 1;
                        }
                    }
                });

                if (flag == 0) {
                    // get order information
                    var order = new OrderViewModel(IdOrder, IdCustomer, StartWeek, FinishWeek/*, Quantity*/);
                    AllPost.DataOrder = order;

                    // get data production
                    MyProduction.init();

                    var countAllItems = 0;
                    var countCompletedItems = 0;
                    $('.pProductionTag').each(function () {
                        countAllItems++;

                        var ProductId = $(this).children('.ProductId').val();
                        var Kind = $(this).children('.Kind').val();
                        var Size = $(this).children('.Size').val();
                        var Weight = $(this).children('.Weight').val();
                        var Quantity = $(this).children('.Quantity').val();
                        var ProductsInBag = $(this).children('.ProductsInBag').val();

                        var errorAdd = $(this).next("p").children(".Error");

                        if (!ProductId || !Kind || !Size || !Quantity) {
                            var textError = "";
                            if (!ProductId) {
                                textError += "Product Id";
                            }
                            if (!Kind) {
                                if (textError.length > 0) {
                                    textError += ", ";
                                }
                                textError += "Kind";
                            }
                            if (!Size) {
                                if (textError.length > 0) {
                                    textError += ", ";
                                }
                                textError += "Size";
                            }
                            if (!Quantity) {
                                if (textError.length > 0) {
                                    textError += ", ";
                                }
                                textError += "Quantity";
                            }
                            if (!ProductsInBag) {
                                if (textError.length > 0) {
                                    textError += ", ";
                                }
                                textError += "Products/Bag";
                            }

                            textError += " must to be filled.";

                            $(errorAdd).text(textError).show().fadeOut(5000);
                        }
                        else {

                            var strError1, strError2, strError;
                            strError1 = "";
                            strError2 = "";
                            strError = "";
                            // check
                            $.ajax({
                                type: "GET",
                                contentType: "application/json; charset=utf-8",
                                url: '@Url.Action("IsProductExisted", "Order")',
                                data: { "id": ProductId },
                                dataType: "json",
                                async: false,
                                beforeSend: function () {//alert();
                                },
                                success: function (data) {
                                    if (data.result == false) {
                                        //$(errorAdd).text("Product id hasn't existed in the system yet. Please check again.").show().fadeOut(5000);
                                        strError1 = "Product id";
                                        flag = 2;
                                    }
                                },
                            });

                            $.ajax({
                                type: "GET",
                                contentType: "application/json; charset=utf-8",
                                url: '@Url.Action("IsKindNameExisted", "Order")',
                                data: { "kindName": Kind },
                                dataType: "json",
                                async: false,
                                beforeSend: function () {//alert();
                                },
                                success: function (data) {
                                    if (data.result == false) {
                                        //$(errorAdd).text("The kind hasn't existed in the system yet. Please check again.").show().fadeOut(5000);
                                        strError2 = "Kind";
                                        flag = 2;
                                    }
                                }
                            });

                            if (flag != 0) {
                                strError = strError1;
                                if (strError.length > 0 && strError2.length > 0 ) {
                                    strError += ", " + strError2;
                                } else {
                                    strError = strError2;
                                }

                                strError += " hasn't existed in the system yet. Please check again.";
                                $(errorAdd).text(strError).show().fadeOut(5000);
                            }

                            if (flag == 0) {
                                var production = new ProductionViewModel(ProductId, Kind, Size, Weight, Quantity, ProductsInBag);
                                MyProduction.Data.push(production);
                                countCompletedItems++;
                            }
                        }
                    });

                    if (flag == 0 && countAllItems == countCompletedItems) {
                        if (MyProduction.Data.length == 0) {
                            $("#notification").text("There is no product in cart. Please check again.").show().fadeOut(5000);
                            return;
                        } else {
                            AllPost.DataProduction = MyProduction.Data;
                            AllPost.post();
                        }
                    }
                }
            }
        });

        /*
        $('#btnGetData').click(function (e) {
            e.preventDefault();
            var flag = 0;

            // get data order
            var IdOrder = $('#orderid').val();
            var IdCustomer = $('#customerid').val();
            var StartWeek = $('#startweek').val();
            var FinishWeek = $('#finishweek').val();

            if (!IdOrder || !IdCustomer || !StartWeek || !FinishWeek) {
                alert("Wrong data! check Order Information");
                return;
            } else {
                var order = new OrderViewModel(IdOrder, IdCustomer, StartWeek, FinishWeek);
                AllPost.DataOrder = order;
            }

            // get data production
            MyProduction.init();
            $('.pProductionTag').each(function () {
                var ProductId = $(this).children('.ProductId').val();
                var Kind = $(this).children('.Kind').val();
                var Size = $(this).children('.Size').val();
                var Weight = $(this).children('.Weight').val();
                var Quantity = $(this).children('.Quantity').val();
                if (!ProductId || !Kind || !Size || !Quantity) {
                    alert("Production Wrongs data!");
                    flag = 1;
                    return;
                }
                else {
                    var production = new ProductionViewModel(ProductId, Kind, Size, Weight, Quantity);
                    MyProduction.Data.push(production);
                }
            });

            if (MyProduction.Data.length == 0) {
                flag = 1;
                alert("There are no Production!");
                return;
            }

            if (flag == 1) {
                alert("Enter wrong data!");
                return;
            }

            AllPost.DataProduction = MyProduction.Data;
            AllPost.post();
        });
        */

        // function casting
        function OrderViewModel(IdOrder, IdCustomer, StartWeek, FinishWeek/*, Quantity*/) {
            var self = this;
            self.IdOrder = IdOrder;
            self.IdCustomer = IdCustomer;
            self.StartWeek = StartWeek;
            self.FinishWeek = FinishWeek;
            //self.Quantity = Quantity;
        }

        // productView
        function ProductionViewModel(ProductId, Kind, Size, Weight, Quantity, ProductsInBag) {
            var self = this;
            self.ProductId = ProductId;
            self.Kind = Kind;
            self.Size = Size;
            self.Weight = Weight;
            self.Quantity = Quantity;
            self.ProductsInBag = ProductsInBag;
        }
        var MyProduction = function () {
            return {

                init: function () {
                    MyProduction.Data = new Array();
                },
            }
        }();

        // all post
        var AllPost = function () {
            return {
                PostUrl: null,

                post: function () {
                    postData = { productions: AllPost.DataProduction, orderViewModel: AllPost.DataOrder };
                    $.ajax({
                        url: '/Order/SaveToDB',
                        type: 'POST',
                        dataType: 'json',
                        data: JSON.stringify(postData),
                        contentType: 'application/json; charset=utf-8',
                        success: function (data) {
                            //alert(data.responseText);
                            if (data.result == false) {
                                alert("Some kind fields are invalid.");
                            } else {
                                alert("Create new order completely!");
                                $('form').submit();
                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            //alert(data.responseText);
                        }
                    });
                }

            }
        }();
    </script>
    
    @*Add Production Event Handler*@
    <script type="text/javascript">
        var index = 1;
        $('#btnAddNewRow').click(function () {
            index += 1;
            addProductionOrder(index, "", "", "", "", "");
        });

        // add production function
        function addProductionOrder(index, ProductId, Kind, Size, Weight, Quantity, ProductsInBag) {
            $('#productionArea').append('<p class="pProductionTag">' +
                           '<b>Pro. Id </b><input style="width: 150px" type="text" class="ProductId textInput requiredInput" id="iProductId' + index + '"placeholder="Product Id" required >' +
                           '<b>Kind </b><input type="text" style="width: 100px" class="Kind requiredInput" id="iKind' + index + '"placeholder="Kind" required>' +
                           '<b>Size </b><input type = "number" min="0" class="Size inputItem requiredInput" id="iSize' + index + '" placeholder="Size" required>' +
                           '<b>Weight </b><input type = "number" min="0" step = "any" class="Weight inputItem" id="iWeight' + index + '" placeholder="Weight">' +
                           '<b>Qty </b><input type = "number" min="0" class="Quantity inputItem requiredInput" id="iQuantity' + index + '" placeholder="Quantity" required>' +
                           '<b>Products/Bag </b><input type = "number" min="0" class="ProductsInBag inputItem requiredInput" id="iProductsInBag' + index + '" placeholder="Number of oroducts in bag" required>' +
                           '<a href="#" id="remove">Remove </a> </p><p><span style="display: none; color: red;" class="Error" id="errorAdd' + index + '"></span></p>');

            // remove additional elements
            $(document).on("click", "#remove ", function () {
                $(this).parents('p').remove();
                return false;
            });

            $("#iProductId" + index).val(ProductId);
            $("#iKind" + index).val(Kind);
            $("#iSize" + index).val(Size);
            $("#iWeight" + index).val(Weight);
            $("#iQuantity" + index).val(Quantity);
            $("#iProductsInBag" + index).val(ProductsInBag);

            var productid = $("#iProductId" + index);
            var errorAdd = $("#errorAdd" + index);
            $(productid).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/Order/GetProducts',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item,
                                    value: item
                                }
                            }));
                        },
                    })
                },
                messages: {
                    noResults: '',
                    results: function () { }
                },
                select: function (event, ui) {
                    $(productid).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });

            $(productid).blur(function () {
                var productId = $(this).val();

                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("IsProductExisted", "Order")',
                    data: { "id": productId },
                    dataType: "json",
                    beforeSend: function () {//alert();
                    },
                    success: function (data) {
                        if (data.result == false) {
                            $(errorAdd).text("Product id hasn't existed in the system yet. Please check again.").show().fadeOut(5000);
                        }
                    }
                });
            });

            var kind = $("#iKind" + index);
            $(kind).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/Order/GetKinds',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item.Name,
                                    value: item.Name
                                }
                            }));
                        },
                    })
                },
                messages: {
                    noResults: '',
                    results: function () { }
                },
                select: function (event, ui) {
                    $(kind).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });

            $(kind).blur(function () {
                var kindName = $(this).val();

                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("IsKindNameExisted", "Order")',
                    data: { "kindName": kindName },
                    dataType: "json",
                    beforeSend: function () {//alert();
                    },
                    success: function (data) {
                        if (data.result == false) {
                            $(errorAdd).text("The kind hasn't existed in the system yet. Please check again.").show().fadeOut(5000);
                        }
                    }
                });
            });

            jQuery(".inputItem").keydown(function (event) {
                // Allow: backspace, delete, tab, escape, enter and .
                if (jQuery.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
                    // Allow: Ctrl+A
                    (event.keyCode == 65 && event.ctrlKey === true) ||
                    // Allow: home, end, left, right
                    (event.keyCode >= 35 && event.keyCode <= 40)) {

                    return;
                }
                else {
                    // Ensure that it is a number and stop the keypress
                    if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                        event.preventDefault();
                    }
                    else {
                        var $focused = $(':focus');
                        if ($focused.val().length >= 10) {
                            $focused.keydown(function (event) {
                                event.preventDefault();
                            })
                        }
                    }
                }
            });

            var size = $("#iSize" + index);
            var quantity = $("#iQuantity" + index);
            $(size).blur(function () {
                var value = $(this).val();

                if (value.length == 0 || parseInt(value) == 0) {
                    $(errorAdd).text("The field is required and value has to be greater than 0. Please check again.").show().fadeOut(5000);
                }
            });
            $(quantity).blur(function () {
                var value = $(this).val();

                if (value.length == 0 || parseInt(value) == 0) {
                    $(errorAdd).text("The field is required and value has to be greater than 0. Please check again.").show().fadeOut(5000);
                }
            });
        }

        $("#contentPaste").on("paste", function (e) {
            // only execute when after finishing paste process
            setTimeout(function () {
                var text = "";

                // get elements
                var dataContainer = document.getElementById("contentPaste");
                var data = dataContainer.getElementsByTagName("table")[0];
                var listRows = data.getElementsByTagName("tr");

                for (var i = 0; i < listRows.length; i++) {
                    var listCols = listRows[i].getElementsByTagName("td");

                    //text += listCols[0].innerHTML + ", " + listCols[1].innerHTML + ";\n";
                    addProductionOrder(index,
                        listCols[0] == null ? "" : listCols[0].innerText,
                        listCols[1] == null ? "" : listCols[1].innerText,
                        listCols[2] == null ? "" : listCols[2].innerText,
                        listCols[3] == null ? "" : listCols[3].innerText,
                        listCols[4] == null ? "" : listCols[4].innerText,
                        listCols[5] == null ? "" : listCols[5].innerText);
                    index++;
                }

                //data.remove();
                dataContainer.innerHTML = "Paste here...";

                // get data
                //alert(text);
            },
                0
            );
        });
    </script>

    <script type="text/javascript">

        $("#submitClear").click(function () {
            $("#orderid").val("");
            $("#customerid").val("");
            $("#startweek").val("");
            $("#finishweek").val("");
            //$("#quantity").val("10");
            $("#productionArea").html("");

            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: '@Url.Action("ClearForm", "Order")',
                dataType: "json",
                beforeSend: function () {//alert();
                },
                success: function (data) {
                    $("#Order_IdOrder").focus();
                    $("#cartDiv").find("table").find("tbody").empty();
                }
            });
        });

        $("#orderid").blur(function () {
            var orderId = $("#orderid").val();

            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: '@Url.Action("IsOrderExisted", "Order")',
                data: { "id": orderId },
                dataType: "json",
                beforeSend: function () {//alert();
                },
                success: function (data) {
                    if (data.result == true) {
                        $("#requireIdOrder").text("Order id has already existed in the system. Please check again.").show().fadeOut(5000);
                    }
                }
            });
        });

        

        $("#startweek, #finishweek").blur(function () {
            var startWeekVal = $("#startweek").val();
            var finishWeekVal = $("#finishweek").val();

            if (startWeekVal.length > 0 && finishWeekVal.length > 0) {
                var start = parseInt(startWeekVal, 10);
                var finish = parseInt(finishWeekVal, 10);

                if (start > finish && finish > 0) {
                    $("#invalidWeek").text("The start week must be smaller or equal than finish week.").fadeIn("slow").fadeOut(5000);
                    $(this).focus();
                }
            }
        });

        $("#orderid, #customerid").blur(function () {
            var value = $(this).val();
            if (value.length == 0) {
                $(this).parent("td").next().find(".requireSpan").show().fadeOut(5000);
            }
        });

        jQuery(".inputItem").keydown(function (event) {
            // Allow: backspace, delete, tab, escape, enter and .
            if (jQuery.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
                // Allow: Ctrl+A
                (event.keyCode == 65 && event.ctrlKey === true) ||
                // Allow: home, end, left, right
                (event.keyCode >= 35 && event.keyCode <= 40)) {

                return;
            }
            else {
                // Ensure that it is a number and stop the keypress
                if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                    event.preventDefault();
                }
                else {
                    var $focused = $(':focus');
                    if ($focused.val().length >= 10) {
                        $focused.keydown(function (event) {
                            event.preventDefault();
                        })
                    }
                }
            }
        });

    </script>
}
